// 该文件路径为: src/apis/updateInfo.js
import axiosInstance from "@/apis/axiosInstance";

//更新用户信息
export const updateInfo = async (userData) => {
  try {
    const response = await axiosInstance.patch("/update/userInfo", userData, {
      headers: {
        "Content-Type": "application/json",
      }
    });
    return response.data;
  } catch (error) {
    console.error("Error in updateInfo:", error); // 添加日志
    throw new Error(error.response ? error.response.data.msg : error.message);
  }
};

//扣除余额
export const deductBalance = async (amount) => {
  try {
    const response = await axiosInstance.post("/update/deduct-balance", null, {
      params: { amount }
    });
    return response.data;
  } catch (error) {
    console.error("Error in deductBalance:", error);
    throw new Error(error.response ? error.response.data.msg : error.message);
  }
};

//增加余额
export const addBalance = async (amount) => {
  try {
    const response = await axiosInstance.post("/update/add-balance", null, {
      params: { amount }
    });
    return response.data;
  } catch (error) {
    console.error("Error in addBalance:", error);
    throw new Error(error.response ? error.response.data.msg : error.message);
  }
};


// 更新购物车商品数量
export const updateCartItemQuantity = async (cartId, quantity) => {
  try {
    const response = await axiosInstance.patch(`/update/cart/quantity`, null, {
      params: { cartId, quantity }
    });
    return response.data;
  } catch (error) {
    console.error("Error in updateCartItemQuantity:", error);
    if (error.response) {
      console.error("Response data:", error.response.data);
      console.error("Response status:", error.response.status);
      console.error("Response headers:", error.response.headers);
    }
    throw new Error(error.response ? error.response.data.msg : error.message);
  }
};

// 从购物车中删除商品
export const removeCartItem = async (cartId) => {
  try {
    const response = await axiosInstance.delete(`/update/cart/item`, {
      params: { cartId }
    });
    return response.data;
  } catch (error) {
    console.error("Error in removeCartItem:", error);
    throw new Error(error.response ? error.response.data.msg : error.message);
  }
};

//清除购物车
export const clearCart = async () => {
  try {
    const response = await axiosInstance.delete(`/update/cart`);
    return response.data;
  } catch (error) {
    console.error("Error in clearCart:", error);
    throw new Error(error.response ? error.response.data.msg : error.message);
  }
};

// 添加商品到购物车
export const addCartItem = async (productId, quantity) => {
  try {
    const response = await axiosInstance.post(`/update/cart/item`, null, {
      params: { productId, quantity }
    });
    return response.data;
  } catch (error) {
    console.error("Error in addCartItem:", error);
    throw new Error(error.response ? error.response.data.msg : error.message);
  }
};